package com;

import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;

/**
 * 比较字符串直接相加和StringBuilder的效率
 */
@State(Scope.Thread)
@BenchmarkMode({Mode.Throughput})
@Warmup(iterations = 3, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 10, time = 5, timeUnit = TimeUnit.MICROSECONDS)
@Threads(16)
@Fork(4)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public class StringBuilderBenchmark {

    private static LongAdder     longAdder     = new LongAdder();
    private static AtomicInteger atomicInteger = new AtomicInteger();

    // @Benchmark
    // public void testStringAdd() {
    //     String a = "";
    //     for (int i = 0; i < 10; i++) {
    //         a += i;
    //     }
    // }
    //
    // @Benchmark
    // public void testStringBuilderAdd() {
    //     StringBuilder sb = new StringBuilder();
    //     for (int i = 0; i < 10; i++) {
    //         sb.append(i);
    //     }
    // }
    @Benchmark
    public void testLongAdder() {
        longAdder.increment();
    }

    @Benchmark
    public void testAtomicInteger() {
        atomicInteger.incrementAndGet();
    }

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder().include(StringBuilderBenchmark.class.getSimpleName()).build();
        new Runner(opt).run();
        // longAdder.increment();
    }

}